package com.webvihar.access2db.builders;

import com.webvihar.access2db.model.ShowQueryResult;
import com.webvihar.access2db.restapi.A2DbHttpHelper;
import com.webvihar.access2db.restapi.A2DbRunShowQueryRequest;
import com.webvihar.access2db.restapi.A2DbUrlBuilder;
import com.webvihar.access2db.restapi.A2DbWebResult;
import com.webvihar.access2db.restapi.AbstractA2DbWebRequest;
import com.webvihar.access2db.restapi.IA2DbWebRequestDelegate;
import com.webvihar.common.builders.JsonBuilder;
import com.webvihar.common.utils.HttpResult;
import com.webvihar.common.utils.Logger;

/**
 * @author Viswanath Kumar Sandu
 * 
 */
public class RunShowQueryBuilder implements IA2DbWebRequestDelegate{
    
	private A2DbWebResult<ShowQueryResult> runQuery(AbstractA2DbWebRequest a2dbWebRequest) {
		A2DbRunShowQueryRequest request = (A2DbRunShowQueryRequest)a2dbWebRequest;
	    A2DbHttpHelper httpHelper = getHttpHelper();
	    HttpResult httpResult = httpHelper.postString(A2DbUrlBuilder.getRunShowQuery(request.encoded, request.host, request.port, request.username, request.password, request.dbname, request.query),"");
		A2DbWebResult<ShowQueryResult> webResult = new A2DbWebResult<ShowQueryResult>();
		if(httpResult != null) {
			Logger.logInfo("HttpResult", httpResult.result);
			ShowQueryResult runQueryResponse = new JsonBuilder().getEntityForJson(httpResult.result, ShowQueryResult.class);
    		webResult.successful = httpResult.statusCode == 200;
    		webResult.entity = runQueryResponse;
		}
		return webResult;
	}

	private A2DbHttpHelper getHttpHelper() {
		return (new A2DbHttpHelper());
	}

	@SuppressWarnings("unchecked")
	public <T> A2DbWebResult<T> execute(AbstractA2DbWebRequest a2dbWebRequest) {
		return (A2DbWebResult<T>) runQuery(a2dbWebRequest);
	}
}
